package com.heng.StampLockDemo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.StampedLock;

public class StampLockDemo1 {
    static int number = 37;
    static StampedLock stampedLock = new StampedLock();
    public void write() {
        long stamp = stampedLock.writeLock();
        System.out.println(Thread.currentThread().getName()+"\t写线程准备修改");
        try {
            number += 13;

        }finally {
            stampedLock.unlockWrite(stamp);
        }
        System.out.println(Thread.currentThread().getName()+"\t写线程结束修改");
    }
    //悲观读，读没有完成时写锁无法获得
    public void read(){
        long stamp = stampedLock.readLock();
        System.out.println(Thread.currentThread().getName()+"\t come in");
        for (int i = 0; i < 4; i++) {
            try{
                TimeUnit.SECONDS.sleep(1);
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            int result = number;
            System.out.println(Thread.currentThread().getName()+"\tresult:"+result);
            System.out.println("写线程没有修改成功，读锁时 写锁无法介入");
        }finally {
            stampedLock.unlockRead(stamp);
        }
    }

    public static void main(String[] args) {
        StampLockDemo1 resource = new StampLockDemo1();
        new Thread(()->{
            resource.read();
        },"readThread").start();

        try{
            TimeUnit.SECONDS.sleep(1);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            resource.write();
        },"writeThread").start();

        try{TimeUnit.SECONDS.sleep(5);}catch (InterruptedException e) {e.printStackTrace();}

        System.out.println(number);

    }
}
